/**
 * 计算菜单和缓存路由
 */

import { reactive, ref, watch } from 'vue';
import { useRouter, useRoute } from "vue-router";
import _ from 'lodash';

function getDateTime() {
  return new Date().getTime();
}

/**
 * 生成随机且不重复的id
 * @param {String} prefix 前缀
 */
function renderRandomId(prefix = 'id') {
  const time = getDateTime();
  const randomNumber = Math.random() * 1e18;
  return `${prefix}${time}${randomNumber}`;
}



function getMenu(routerList = [], menuList = []) {
  // console.log({ routerList, menuList })

  routerList.forEach(_router => {
    const meta = _.get(_router, 'meta', null)
    const _menu = {
      id: renderRandomId('menu'),
      path: _router.path,
      ...(meta || {}),
    };
    // console.log({ meta, _menu, _router })

    if (_router.children && _router.children.length) {
      _menu.children = [];
      getMenu(_router.children, _menu.children)
    }

    /**
     * hidden为true
     * redirect重定向的
     */
    let hidden = false;

    if (meta) {
      if (meta.hidden) {
        hidden = true;
      }
      else if (_router.redirect === undefined) {
        hidden = false
      } else {
        hidden = true
      }
    }
    // console.log({ hidden, _menu })
    if (!hidden) {
      // console.log("追加")
      menuList.push(_menu)
    }

  })
  // console.log({ menuList })
}

const useCompoutedRouter = function () {
  const router = useRouter();
  const route = useRoute();

  const activeMenu = ref("home");
  const menuList = reactive([]);
  const include = reactive([]);

  /**
   * 计算菜单 和  缓存列表
   */
  const routes = _.get(router, 'options.routes.0.children', []) || [];

  getMenu(routes, menuList);

  // console.log({ routes, menuList }, "=================================");

  watch(
    () => route.meta,
    ({ name }) => (activeMenu.value = name)
  );

  return {
    activeMenu,
    menuList,
    include,
  };
}

export default useCompoutedRouter;